package com.ruoyi.api.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.workstation.domain.User;
import com.ruoyi.workstation.domain.UserFirmwarePackage;
import com.ruoyi.workstation.service.IUserFirmwarePackageService;
import com.ruoyi.workstation.service.IUserService;
import com.ruoyi.workstation.service.impl.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 固件包
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/user/firmware")
public class ApiUserFirmwareController {
    private static final Logger log = LoggerFactory.getLogger(ApiUserFirmwareController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IUserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IUserFirmwarePackageService userFirmwarePackageService;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 固件检查
     *
     * @param version
     */
    @GetMapping("/check/{type}/{version}")
    public AjaxResult check(HttpServletRequest request, @PathVariable("type") int type, @PathVariable("version") long version) {
        try {
            Long userId = tokenService.getLoginUserId(request);
            User user = userService.selectUserByUserId(userId);
            if (user == null) {
                return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
            }
            UserFirmwarePackage userFirmwarePackage = userFirmwarePackageService.check(type);
            if (userFirmwarePackage.getVersion() > version) {
                String url = serverConfig.getUrl() + userFirmwarePackage.getFileName();
                userFirmwarePackage.setUrl(url);
                return AjaxResult.success(userFirmwarePackage);
            } else {
                return AjaxResult.success();
            }
        } catch (Exception e) {
            log.error("type:" + type + "version:" + version, e);
            return AjaxResult.error();
        }
    }

}
